﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.zjyApplication.Commands.Permissionses
{
    public class DeletedRolePermissionsHandler : IRequestHandler<DeletedRolePermissionCommand, Result>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletedRolePermissionsHandler> _logger;

        /// <summary>
        /// 角色权限表
        /// </summary>
        private readonly IBaseRepository<RolePermissions> _rolePermissionsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="rolePermissionsRepository"></param>
        public DeletedRolePermissionsHandler(ILogger<DeletedRolePermissionsHandler> logger,
                                             IBaseRepository<RolePermissions> rolePermissionsRepository)
        {
            _logger = logger;
            _rolePermissionsRepository = rolePermissionsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeletedRolePermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var query = await (await _rolePermissionsRepository.GetAll()).Where(x => x.RolePermissionsId == request.RolePermissionsId).FirstOrDefaultAsync();
                if (query != null)
                {
                    query.IsDeleted = true;
                }
                var res = await _rolePermissionsRepository.Update(query);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "删除角色权限成功";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("删除角色权限异常" + ex.Message);
            }
            return result;
        }
    }
}
